//
//  CoreDataManager.swift
//  CoreDataSwift
//
//  Created by liuxiang on 2018/1/9.
//  Copyright © 2018 liuxiang. All rights reserved.
//
import Foundation
import UIKit
import CoreData

class CoreDataManager: NSObject {
    
    static let singleCoreDataManager = CoreDataManager()
    
    private lazy var mb: NSManagedObjectModel? = {
        var mb = NSManagedObjectModel.mergedModel(from: nil)
        return mb
    }()
   
    lazy var moc: NSManagedObjectContext = {
        var moc = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
        moc.persistentStoreCoordinator = self.persistentStoreCoordinator
        NotificationCenter.default.addObserver(CoreDataManager.singleCoreDataManager, selector: #selector(mergeChanges) , name: NSNotification.Name.NSManagedObjectContextDidSave, object: nil)
        return moc
    }()
    
    lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
        if self.mb == nil {return nil}
        var psc = NSPersistentStoreCoordinator(managedObjectModel: self.mb!)
         let storePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last!.appending("/demo.db")
        if let bundleDbPath = Bundle.main.path(forResource: "demo", ofType: "db") {
            do {
                print("bundleDbPath = \(bundleDbPath)")
                try FileManager.default.copyItem(atPath: bundleDbPath, toPath: storePath)
            }catch  {
                let err = error as NSError
                print("copy file error \(err.localizedDescription)")
            }
        }
        
        print("sotrePath = \(storePath)")
        let url = URL(fileURLWithPath: storePath)
        do {
            try psc.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
        } catch {
             
        }
       
       return psc
    }()
    
    private override init() {
        
    }

    @objc func mergeChanges(_ not: Notification) {
        if not.object as? NSManagedObjectContext != self.moc {
            self.performSelector(onMainThread: #selector(updateMainContext), with: not, waitUntilDone: false)
        }
    }
    
    @objc func updateMainContext(not: Notification) {
        self.moc.mergeChanges(fromContextDidSave: not)
    }
    
    
    
}
